//
//  XGUserAccountManager.swift
//  TodayNews
//
//  Created by monkey on 2020/5/12.
//  Copyright © 2020 itcast. All rights reserved.
//

import Foundation
import LeanCloud

class XGUserAccountManager
{
    /// 昵称
    var screenName: String?
    /// 邮箱
    var email: String?
    /// 手机号
    var phoneNumber: String?
    /// 是否客户端登录
    var isClientAccount: Bool = false
    /// 头像
    var userIcon: String?
    /// 单例
    public static let shared = XGUserAccountManager()
    
    var isLogin: Bool {
        return screenName != nil
    }
    
    func saveUserAccount(userModel: AnyObject?) -> Void
    {
        if let userModel = userModel as? UMSocialUserInfoResponse {
            screenName = userModel.name
            userIcon = userModel.iconurl
            isClientAccount = false
        }
        
        if let userModel = userModel as? LCUser {
            screenName = userModel.screenName?.stringValue
            email = userModel.email?.stringValue
            phoneNumber = userModel.mobilePhoneNumber?.stringValue
            isClientAccount = true
        }
        
        UserDefaults.standard.set(screenName, forKey: "screenName")
        UserDefaults.standard.set(email, forKey: "email")
        UserDefaults.standard.set(phoneNumber, forKey: "phoneNumber")
        UserDefaults.standard.set(isClientAccount, forKey: "isClientAccount")
        UserDefaults.standard.set(userIcon, forKey: "userIcon")
        UserDefaults.standard.synchronize()
    }
    
    func removeUserAccount() -> Void
    {
        UserDefaults.standard.removeObject(forKey: "screenName")
        UserDefaults.standard.removeObject(forKey: "email")
        UserDefaults.standard.removeObject(forKey: "phoneNumber")
        UserDefaults.standard.removeObject(forKey: "isClientAccount")
        UserDefaults.standard.removeObject(forKey: "userIcon")
        UserDefaults.standard.synchronize()
    }

    private init()
    {
        screenName = UserDefaults.standard.string(forKey: "screenName")
        email = UserDefaults.standard.string(forKey: "email")
        phoneNumber = UserDefaults.standard.string(forKey: "phoneNumber")
        isClientAccount = UserDefaults.standard.bool(forKey: "isClientAccount")
        userIcon = UserDefaults.standard.string(forKey: "userIcon")
    }
}
